package lancooPaperRateSelf;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.lancooznbk.R;
import com.example.lancooznbk.presenter.PaperDef;

import org.apache.commons.lang3.StringEscapeUtils;

import lancooControl.Control;
import lancooControl.CustomEditText;

import static testPaperCTCS.GuessTestingPaperActivity.InforGuessTesting;
import static testPaperJBFX.BasicReviewPaperActivity.InforBasicReview;
import static testPaperNDFX.DifficultReviewPaperActivity.InforDifficultReview;
import static testPaperWrong.WrongQuesPaperActivity.InforWrongQues;


/**
 * Created by Administrator on 2017/4/25.
 */
public class RateKtxjzAdapter extends BaseAdapter {


    private Context mContext;
    private LayoutInflater mInflater;
    private int ItemSum;
    private int PaperID;
    private int ModelFrom;//试卷来源

    private String answer = "";//正确答案
    private String stuAssess = "";//自评/机评结果
    private double score;//小题分值


    private ViewHolder holder = null;
    public final class ViewHolder {
        TextView TvAnswer;
        RadioGroup Rg;
        RadioButton RbA;
        RadioButton RbB;
        RadioButton RbC;
        CustomEditText EdtScore;


        private ViewHolder(View convertView) {
            TvAnswer = (TextView) convertView.findViewById(R.id.tv_answer);
            Rg = (RadioGroup) convertView.findViewById(R.id.rg);
            RbA = (RadioButton) convertView.findViewById(R.id.rb_a);
            RbB = (RadioButton) convertView.findViewById(R.id.rb_b);
            RbC = (RadioButton) convertView.findViewById(R.id.rb_c);
            EdtScore = (CustomEditText) convertView.findViewById(R.id.edt_score);
        }

    }

    public RateKtxjzAdapter(Context context, int itemSum, int paperID, int modelFrom) {
        this.mContext = context;
        mInflater = LayoutInflater.from(context);
        this.ItemSum = itemSum;
        this.PaperID = paperID;
        this.ModelFrom = modelFrom;
    }

    @Override
    public int getCount() {
        return ItemSum;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.adapter_rate_ktxjz_item, null);
            holder = new ViewHolder(convertView);

            if(ModelFrom == PaperDef.FROM_BASE_REVIEW) {
                answer = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(0).getAnswer();
            }else if(ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW){
                answer = InforDifficultReview.getQueList().get(0).getAnswer();
            }else if(ModelFrom==PaperDef.FROM_GUESS_REVIEW){
                answer = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(0).getAnswer();
            }else if(ModelFrom==PaperDef.FROM_BASE_REVIEW_WRONG||ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW_WRONG){
                answer = InforWrongQues.get(PaperID).getQueList().get(0).getAnswer();
            }
            answer = StringEscapeUtils.unescapeXml(answer);
            holder.TvAnswer.setText(Html.fromHtml(answer));

            if(ModelFrom==PaperDef.FROM_GUESS_REVIEW){

                holder.Rg.setVisibility(View.GONE);
                holder.EdtScore.setVisibility(View.VISIBLE);

                holder.EdtScore.setText(GetStuAssess());
                holder.EdtScore.addTextChangedListener(new MyWatcher(-1,1));

            }else {

                holder.Rg.setVisibility(View.VISIBLE);
                holder.EdtScore.setVisibility(View.GONE);

                setRadioGroup();
                holder.Rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                        if (checkedId == holder.RbA.getId()) {
                            setStuAssess("优秀");
                        } else if (checkedId == holder.RbB.getId()) {
                            setStuAssess("一般");
                        } else if (checkedId == holder.RbC.getId()) {
                            setStuAssess("较差");
                        }
                    }
                });

            }

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        return convertView;
    }

    /*
    * 设置自评
    * */
    private void setRadioGroup(){

        if(GetStuAssess().equals("优秀")){
            holder.RbA.setChecked(true);
            holder.RbB.setChecked(false);
            holder.RbC.setChecked(false);
        }else if(GetStuAssess().equals("一般")){
            holder.RbA.setChecked(false);
            holder.RbB.setChecked(true);
            holder.RbC.setChecked(false);
        }else if(GetStuAssess().equals("较差")){
            holder.RbA.setChecked(false);
            holder.RbB.setChecked(false);
            holder.RbC.setChecked(true);
        } else if(GetStuAssess().equals("")){
            holder.RbA.setChecked(false);
            holder.RbB.setChecked(false);
            holder.RbC.setChecked(false);
        }

    }

    /*
    * 获取当前自评结果
    * */
    private String GetStuAssess(){
        String strStuAssess = "";
        if(ModelFrom == PaperDef.FROM_BASE_REVIEW) {
            strStuAssess = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(0).getStuAssess();
        }else if(ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW){
            strStuAssess = InforDifficultReview.getQueList().get(0).getStuAssess();
        }else if(ModelFrom==PaperDef.FROM_GUESS_REVIEW){
            strStuAssess = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(0).getStuAssess();
            score = InforGuessTesting.getPaperContent().get(PaperID).getScore();
        }else if(ModelFrom==PaperDef.FROM_BASE_REVIEW_WRONG||ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW_WRONG){
            strStuAssess = InforWrongQues.get(PaperID).getQueList().get(0).getStuAssess();
        }
        return strStuAssess;
    }

    /*
       * 写入当前自评结果
       * */
    private void setStuAssess(String strStuAssess){

        if(ModelFrom == PaperDef.FROM_BASE_REVIEW) {
            InforBasicReview.getPaperContent().get(PaperID).getQueList().get(0).setStuAssess(strStuAssess);
            String thisStuAnswer = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(0).getStuAnswer();
            String thisAnswer = InforBasicReview.getPaperContent().get(PaperID).getQueList().get(0).getAnswer();

            InforBasicReview.getPaperContent().get(PaperID).setStuAnswerNewAll(thisStuAnswer);
            InforBasicReview.getPaperContent().get(PaperID).setStuAssessNewAll(strStuAssess);

            double correctRate= 0.0;
            if(!strStuAssess.equals("")){
                if (strStuAssess.equals("优秀")||strStuAssess.equals("一般")) {
                    correctRate = 1.0;
                }else{
                    correctRate = 0.0;
                }
            }else{
                if(thisStuAnswer.equals(thisAnswer)){
                    correctRate = 1.0;
                }else{
                    correctRate = 0.0;
                }
            }
            InforBasicReview.getPaperContent().get(PaperID).setCorrectRate(correctRate);
            int quesAnsweredItemCount = 0;
            if(strStuAssess.equals("")&&thisStuAnswer.equals("")){
                quesAnsweredItemCount = 0;
            }else{
                quesAnsweredItemCount = 1;
            }
            InforBasicReview.getPaperContent().get(PaperID).setAnsweredItemCount(quesAnsweredItemCount);

            if(!strStuAssess.equals("")){
                InforBasicReview.setState(1);
            }else{
                InforBasicReview.setState(0);
            }
        }else if(ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW){
            InforDifficultReview.getQueList().get(0).setStuAssess(strStuAssess);
            String thisStuAnswer = InforDifficultReview.getQueList().get(0).getStuAnswer();
            String thisAnswer = InforDifficultReview.getQueList().get(0).getAnswer();

            InforDifficultReview.setStuAnswerNewAll(thisStuAnswer);
            InforDifficultReview.setStuAssessNewAll(strStuAssess);

            double correctRate= 0.0;
            if(!strStuAssess.equals("")){
                if (strStuAssess.equals("优秀")||strStuAssess.equals("一般")) {
                    correctRate = 1.0;
                }else{
                    correctRate = 0.0;
                }
            }else{
                if(thisStuAnswer.equals(thisAnswer)){
                    correctRate = 1.0;
                }else{
                    correctRate = 0.0;
                }
            }
            InforDifficultReview.setCorrectRate(correctRate);
            int quesAnsweredItemCount = 0;
            if(strStuAssess.equals("")&&thisStuAnswer.equals("")){
                quesAnsweredItemCount = 0;
            }else{
                quesAnsweredItemCount = 1;
            }
            InforDifficultReview.setAnsweredItemCount(quesAnsweredItemCount);

            if(!strStuAssess.equals("")){
                InforDifficultReview.setState(1);
            }else{
                InforDifficultReview.setState(0);
            }
        }else if(ModelFrom==PaperDef.FROM_GUESS_REVIEW){
            InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(0).setStuAssess(strStuAssess);
            String thisStuAnswer = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(0).getStuAnswer();
            String thisAnswer = InforGuessTesting.getPaperContent().get(PaperID).getQueList().get(0).getAnswer();

            InforGuessTesting.getPaperContent().get(PaperID).setStuAnswerNewAll(thisStuAnswer);
            InforGuessTesting.getPaperContent().get(PaperID).setStuAssessNewAll(strStuAssess);

            double correctRate= 0.0;
            if(!strStuAssess.equals("")){
                correctRate = Control.getCorrectRate(Float.valueOf(strStuAssess), (float) score);
            }else{
                if(thisStuAnswer.equals(thisAnswer)){
                    correctRate = 1.0;
                }else{
                    correctRate = 0.0;
                }
            }
            InforGuessTesting.getPaperContent().get(PaperID).setCorrectRate(correctRate);
            int quesAnsweredItemCount = 0;
            if(strStuAssess.equals("")&&thisStuAnswer.equals("")){
                quesAnsweredItemCount = 0;
            }else{
                quesAnsweredItemCount = 1;
            }
            InforGuessTesting.getPaperContent().get(PaperID).setAnsweredItemCount(quesAnsweredItemCount);

            if(!strStuAssess.equals("")){
                InforGuessTesting.setState(1);
            }else{
                InforGuessTesting.setState(0);
            }
        }else if(ModelFrom==PaperDef.FROM_BASE_REVIEW_WRONG||ModelFrom==PaperDef.FROM_DIFFERENT_REVIEW_WRONG){

            InforWrongQues.get(PaperID).getQueList().get(0).setStuAssess(strStuAssess);
            String thisStuAnswer = InforWrongQues.get(PaperID).getQueList().get(0).getStuAnswer();
            String thisAnswer = InforWrongQues.get(PaperID).getQueList().get(0).getAnswer();

            InforWrongQues.get(PaperID).setStuAnswerNewAll(thisStuAnswer);
            InforWrongQues.get(PaperID).setStuAssessNewAll(strStuAssess);

            double correctRate= 0.0;
            if(!strStuAssess.equals("")){
                if (strStuAssess.equals("优秀")||strStuAssess.equals("一般")) {
                    correctRate = 1.0;
                }else{
                    correctRate = 0.0;
                }
            }else{
                if(thisStuAnswer.equals(thisAnswer)){
                    correctRate = 1.0;
                }else{
                    correctRate = 0.0;
                }
            }
            InforWrongQues.get(PaperID).setCorrectRate(correctRate);
            int quesAnsweredItemCount = 0;
            if(strStuAssess.equals("")&&thisStuAnswer.equals("")){
                quesAnsweredItemCount = 0;
            }else{
                quesAnsweredItemCount = 1;
            }
            InforWrongQues.get(PaperID).setAnsweredItemCount(quesAnsweredItemCount);

            if(!strStuAssess.equals("")){
                InforWrongQues.get(PaperID).setState(1);
            }else{
                InforWrongQues.get(PaperID).setState(0);
            }

        }

        if(ModelFrom!=PaperDef.FROM_GUESS_REVIEW) {
            setRadioGroup();
        }

    }

    public class MyWatcher implements TextWatcher {
        private int beforeDot;
        private int afterDot;
        /**
         * 构造器
         *
         * @param beforeDot 小数点前位数   不限制输入-1
         * @param afterDot  小数点后位数   不限制输入-1
         */
        public MyWatcher(int beforeDot, int afterDot) {
            this.beforeDot = beforeDot;
            this.afterDot = afterDot;
        }


        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.e("====ssss===","==0000==="+s.toString());
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.e("====ssss===","==1111==="+s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            judge(s);
            String strAssess = s.toString();

            if(!strAssess.equals("")){
                if(!strAssess.equals("0")){
                    if(strAssess.endsWith(".")){
                        strAssess = strAssess + "0";
                    }else{
                        if(!strAssess.contains(".")){
                            strAssess=strAssess+".0";
                        }
                    }
                }else{
                    strAssess = "0.0";
                }
            }


            setStuAssess(strAssess);
        }

        @SuppressLint("NewApi")
        private void judge(Editable editable) {
            String temp = editable.toString();
            double thisScore = score;

            if(temp.contains(".")){
                if(Control.getStringFrequency(temp,".")==1){

                    if(temp.indexOf(".")!=temp.length()-1&&!temp.contains("..")) {
                        if (Double.valueOf(temp) > thisScore) {
                            Log.e("===editable====","==00111111==");
                            editable.clear();
                            editable.insert(0, String.valueOf(thisScore));
                            return;
                        }else if(Double.valueOf(temp) < thisScore){
                            Log.e("===xxxxxxx====","==xxxxxxx000=="+temp.substring(temp.indexOf(".")+1));
                            if(!temp.endsWith("5")){

                                if(temp.endsWith("6")||temp.endsWith("7")||temp.endsWith("8")||temp.endsWith("9")){
                                    Double dTemp = (double) Math.rint(Double.valueOf(temp));
                                    temp = String.valueOf(dTemp);
                                    editable.clear();
                                    editable.insert(0, String.valueOf(Double.valueOf(temp)));
                                }else {
                                    if(!temp.equals("0.0")){
                                        int iTemp = (int) Math.floor(Double.valueOf(temp));
                                        temp = String.valueOf(iTemp);
                                        editable.clear();
                                        editable.insert(0, String.valueOf(Double.valueOf(temp)));
                                    }
                                }
                                return;
                            }
                        }
                    }

                }
            }else{
                if (!temp.equals("")&&Double.valueOf(temp) > thisScore) {
                    Log.e("===editable====","==0022222==");
                    editable.clear();
                    editable.insert(0, String.valueOf(thisScore));
                    return;
                }
            }


            int posDot = temp.indexOf(".");
            //直接输入小数点的情况
            if (posDot == 0) {
                editable.insert(0, "0");
                return;
            }
            //连续输入0
            if (temp.equals("00")) {
                editable.delete(1, 2);
                return;
            }

            //连续输入.
            if (temp.contains("..")) {
                editable.delete(temp.length()-1, temp.length());
                return;
            }

            //输入"08" 等类似情况
            if (temp.startsWith("0") && temp.length() > 1 && (posDot == -1 || posDot > 1)) {
                editable.delete(0, 1);
                return;
            }

            //不包含小数点 不限制小数点前位数
            if (posDot < 0 && beforeDot == -1) {
                //do nothing 仅仅为了理解逻辑而已
                return;
            } else if (posDot < 0 && beforeDot != -1) {
                //不包含小数点 限制小数点前位数
                if (temp.length() <= beforeDot) {
                    //do nothing 仅仅为了理解逻辑而已
                } else {
                    editable.delete(beforeDot, beforeDot + 1);
                }
                return;
            }

            //如果包含小数点 限制小数点后位数
            if (temp.length() - posDot - 1 > afterDot && afterDot != -1) {
                editable.delete(posDot + afterDot + 1, posDot + afterDot + 2);//删除小数点后多余位数
            }

        }
    }


}